package com.pda.xinma.ui.xinruku;

import android.annotation.SuppressLint;
import android.app.Instrumentation;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.Gson;
import com.pda.xinma.R;
import com.pda.xinma.adapter.InStoregeAdapter;
import com.pda.xinma.bean.CompleteBean;
import com.pda.xinma.bean.ConnectionBean;
import com.pda.xinma.bean.InStoregeListBean;
import com.pda.xinma.bean.OrderBean;
import com.pda.xinma.bean.ProcessBean;
import com.pda.xinma.bean.ScanBean;
import com.pda.xinma.bean.ScanResultBean;
import com.pda.xinma.bean.SelectBean;
import com.pda.xinma.bean.UserBean;
import com.pda.xinma.bean.WorkSurfaceBean;
import com.pda.xinma.bean.request.CompleteRequest;
import com.pda.xinma.bean.request.ConfirmEntry;
import com.pda.xinma.bean.request.RecommendRequest;
import com.pda.xinma.contract.InStoregeContract;
import com.pda.xinma.dialog.AffirmDialog;
import com.pda.xinma.dialog.RecommendDialog;
import com.pda.xinma.presenter.InStoregePresenter;
import com.pda.xinma.utils.PopUtisl;
import com.pda.xinma.utils.UserUtils;
import com.pda.xinma.view.ScanButView;
import com.pda.xinma.view.datepicker.CustomDatePicker;
import com.pda.xinma.view.datepicker.DateFormatUtils;
import com.wangshen.base.app.AppActivityKey;
import com.wangshen.base.ui.mvp.base.ui.BaseMvpActivity;
import com.wangshen.base.util.SharedPreferencesUtil;
import com.wangshen.base.util.ToastUtils;

import org.json.JSONArray;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = AppActivityKey.INSTOREGEACTIVITY)
public class InStoregeActivity extends BaseMvpActivity<InStoregePresenter> implements InStoregeContract.View {
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_work_surface)
    TextView tvWorkSurface;
    @BindView(R.id.tv_orderNo)
    TextView tvOrderNo;
    @BindView(R.id.tv_warehouseId)
    TextView tvWarehouseId;
    @BindView(R.id.tv_processName)
    TextView tvProcessName;
    @BindView(R.id.sb_scan)
    ScanButView sbScan;
    @BindView(R.id.tv_move_out)
    TextView tvMoveOut;
    @BindView(R.id.tv_detail)
    TextView tvDetail;
    @BindView(R.id.tv_user)
    TextView tvUser;
    @BindView(R.id.tv_connection)
    TextView tvConnection;
    @BindView(R.id.et_actNum)
    EditText etActNum;
    @BindView(R.id.et_diskNum)
    EditText etDiskNum;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_connectionCode)
    TextView tvConnectionCode;
    @BindView(R.id.rv_content)
    RecyclerView rvContent;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    private SelectBean faceBean, warehouseBean, processBean, userBean;
    InStoregeAdapter inStoregeAdapter;

    @Override
    public InStoregePresenter getPresenter() {
        return new InStoregePresenter();
    }

    @Override
    public int getView() {
        return R.layout.activity_in_storege;
    }

    @Override
    public void initView() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        initDatePicker();
        inStoregeAdapter = new InStoregeAdapter(R.layout.item_in_storege_list, new ArrayList<>());
        rvContent.setAdapter(inStoregeAdapter);
        if (TextUtils.isEmpty(SharedPreferencesUtil.getInstance().getString(UserUtils.getInstance().getUserBean().getUserName()+"center",""))){
            presenter.getCenterByUserId();
        }else {
            String center=SharedPreferencesUtil.getInstance().getString(UserUtils.getInstance().getUserBean().getUserName()+"center","");
            faceBean=new Gson().fromJson(center,SelectBean.class);
            tvWorkSurface.setText(faceBean.getName());
        }

      /*  presenter.getOrderByNo("8000482301");
        presenter.scanTheQRCodeToVerify("JB_DM_301");*/
        //tvConnectionCode.performLongClick();
    }

    @Override
    public void initLinsenterner() {
        inStoregeAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.tv_manzSpecId) {
                    presenter.getManzSpecList(inStoregeAdapter.getData().get(position));
                }else if (view.getId() == R.id.tv_delete){
                    AffirmDialog dialog=new AffirmDialog(mContext, new AffirmDialog.OnConfrim() {
                        @Override
                        public void onConfrim() {
                            inStoregeAdapter.getData().remove(position);
                            inStoregeAdapter.notifyDataSetChanged();
                        }
                    });
                    dialog.show("确认删除吗？");
                }
            }
        });
        sbScan.setScanCallBack(new ScanButView.ScanCallBack() {
            @Override
            public void callBack(ScanBean scanBean) {
               /* Instrumentation instrumentation=new Instrumentation();
                instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BRIGHTNESS_DOWN);*/
                if (!TextUtils.isEmpty(scanBean.getCode())) {
                    if (scanBean.getCode().contains("order")) {
                        if (TextUtils.isEmpty(tvConnectionCode.getText().toString())) {
                            showMessage("请先扫接驳位");
                            return;
                        }
                        int lenth = scanBean.getCode().indexOf("A");
                        String order = scanBean.getCode().substring(lenth + 1);
                        if (isSame(order)){
                            showMessage("请不要重复添加订单！");
                            return;
                        }
                        presenter.getOrderByNo(order);
                    } else {
                        presenter.scanTheQRCodeToVerify(scanBean.getCode());
                    }
                }
            }
        });
    }
    private boolean isSame(String order){
        boolean is=false;
        for (InStoregeListBean listBean:inStoregeAdapter.getData()){
            if (order.equals(listBean.getProOrderNo())){
                is=true;
            }
        }
        return is;
    }
    @Override
    public void getData() {

    }

    @Override
    public void setFaceList(List<WorkSurfaceBean> list) {
        List<SelectBean> selectBeans = new ArrayList<>();
        if (list.size() > 0 && TextUtils.isEmpty(tvWorkSurface.getText())){
            SelectBean selectBean=new SelectBean(list.get(0).getCenterName(), list.get(0).getCenterCode());
            faceBean = selectBean;
            tvWorkSurface.setText(selectBean.getName());
            SharedPreferencesUtil.getInstance().putString(UserUtils.getInstance().getUserBean().getUserName()+"center",new Gson().toJson(faceBean));
            return;
        }
        for (WorkSurfaceBean bean : list) {
            selectBeans.add(new SelectBean(bean.getCenterName(), bean.getCenterCode()));
        }
        PopUtisl.showSelectPop(this, selectBeans, tvWorkSurface, new PopUtisl.SelectClick() {
            @Override
            public void onClick(SelectBean bean) {
                faceBean = bean;
                tvWorkSurface.setText(bean.getName());
                SharedPreferencesUtil.getInstance().putString(UserUtils.getInstance().getUserBean().getUserName()+"center",new Gson().toJson(faceBean));
            }
        }, "请选择工作中心");
    }

    @Override
    public void setConnectionList(List<ConnectionBean> list) {
        /*if (TextUtils.isEmpty(tvWarehouseId.getText()) && list.size() > 0){
            warehouseBean = new SelectBean(list.get(0).getDisplayName(), list.get(0).getWarehouseId(), list.get(0).getConnectionCodes());
            tvWarehouseId.setText(warehouseBean.getName());
            tvConnection.setText(warehouseBean.getOther());
            return;
        }*/
        List<SelectBean> selectBeans = new ArrayList<>();
        for (ConnectionBean bean : list) {
            selectBeans.add(new SelectBean(bean.getDisplayName(), bean.getWarehouseId(), bean.getConnectionCodes()));
        }
        PopUtisl.showSelectPop(this, selectBeans, tvWorkSurface, new PopUtisl.SelectClick() {
            @Override
            public void onClick(SelectBean bean) {
                warehouseBean = bean;
                tvWarehouseId.setText(warehouseBean.getName());
                tvConnection.setText(warehouseBean.getOther());
            }
        }, "请选择线边库");
    }

    @Override
    public void setProcessList(List<ProcessBean> list) {
        if (list.size() == 1){
            processBean=new SelectBean(list.get(0).getProcessName(),list.get(0).getProcessId());
            tvProcessName.setText(processBean.getName());
            inStoregeListBean.setFlowId(list.get(0).getFlowId());
            if (!isSame(inStoregeListBean.getProOrderNo())){
                inStoregeAdapter.addData(inStoregeListBean);
            }
            presenter.getComplete(tvOrderNo.getText().toString(), processBean.getId());
            return;
        }
        List<SelectBean> selectBeans = new ArrayList<>();
        for (ProcessBean bean : list) {
            selectBeans.add(new SelectBean(bean.getProcessName(), bean.getProcessId(),bean.getFlowId()));
        }
        PopUtisl.showSelectPop(this, selectBeans, tvWorkSurface, new PopUtisl.SelectClick() {
            @Override
            public void onClick(SelectBean bean) {
                processBean = bean;
                inStoregeListBean.setFlowId(processBean.getOther());
                if (!isSame(inStoregeListBean.getProOrderNo())){
                    inStoregeAdapter.addData(inStoregeListBean);
                }
                tvProcessName.setText(processBean.getName());
                presenter.getComplete(tvOrderNo.getText().toString(), processBean.getId());
            }
        }, "请选择工序");
    }

    @Override
    public void setComplete(CompleteBean complete) {
        try {
            inStoregeListBean.setWanNum(String.valueOf(complete.getActNum()));
            inStoregeListBean.setInNum(String.valueOf(complete.getActNum()));
            inStoregeAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
        etActNum.setText(complete.getActNum() + "");
        etDiskNum.setText(complete.getDiskNum() + "");
        etRemark.setText(complete.getRemark());
        tvUser.setText(complete.getUserIds());
        tvDate.setText(complete.getCompleteTime());
        presenter.getConnectionByCenter(getOrders());
    }
    private String getOrders(){
        String orders="";
        for (InStoregeListBean bean:inStoregeAdapter.getData()){
            if (TextUtils.isEmpty(orders)){
                orders=bean.getProOrderNo();
            }else {
                orders=orders+","+bean.getProOrderNo();
            }
        }
       return orders;
    }
    @Override
    public void setUserList(List<UserBean> list) {
        List<SelectBean> selectBeans = new ArrayList<>();
        for (UserBean bean : list) {
            selectBeans.add(new SelectBean(bean.getUserName(), bean.getUserId()));
        }
        PopUtisl.showSelectPop(this, selectBeans, tvWorkSurface, new PopUtisl.SelectClick() {
            @Override
            public void onClick(SelectBean bean) {
                userBean = bean;
                if (TextUtils.isEmpty(tvUser.getText())) {
                    tvUser.setText(bean.getId());
                } else {
                    if (tvUser.getText().toString().contains(bean.getId())) {
                        showMessage("请勿重复选择！");
                        return;
                    }
                    tvUser.setText(tvUser.getText() + "," + bean.getId());
                }

            }
        }, "请选择工作人员");
    }

    @Override
    public void setManzList(List<SelectBean> list, InStoregeListBean inStoregeListBean) {
        PopUtisl.showSelectPop(this, list, tvWorkSurface, new PopUtisl.SelectClick() {
            @Override
            public void onClick(SelectBean bean) {
                inStoregeListBean.setManzSpecId(bean.getId());
                inStoregeListBean.setManzSpecName(bean.getName());
                inStoregeAdapter.notifyDataSetChanged();
            }
        }, "MANZ盘规格");
    }
    InStoregeListBean inStoregeListBean;
    @Override
    public void setData(OrderBean orderBean) {
        tvOrderNo.setText(orderBean.getProOrderNo());
        InStoregeListBean inStoregeListBean = new InStoregeListBean();
        inStoregeListBean.setArticleId(orderBean.getArticleId());
        inStoregeListBean.setManzSpecId(orderBean.getManzSpecId());
        inStoregeListBean.setModel(orderBean.getModel());
        inStoregeListBean.setGrade(orderBean.getGrade());
        inStoregeListBean.setProOrderNo(orderBean.getProOrderNo());
        inStoregeListBean.setInNum(orderBean.getPlanNum() + "");
        inStoregeListBean.setManzSpecName(orderBean.getManzSpecName());
        this.inStoregeListBean=inStoregeListBean;
        if (!TextUtils.isEmpty(tvOrderNo.getText()) && !TextUtils.isEmpty(tvWorkSurface.getText())) {
            presenter.getCenterList(tvOrderNo.getText().toString(), faceBean.getId());
        }
    }

    @Override
    public void setScanBean(ScanResultBean scanBean) {
        if (scanBean.getType().equals("KW")) {
            tvConnectionCode.setText(scanBean.getCode());
            tvOrderNo.setText("");
            setSaveSuccess();
            inStoregeAdapter.setNewInstance(new ArrayList<>());
            // SharedPreferencesUtil.getInstance().putString(StringKey.STORAGEBIN,stringBaseAppEntity.getData().getCode());
        } else /*if ()*/ {
            ToastUtils.showToast(mContext, "请扫接驳工位？");
            //presenter.getOrderByNo(tvOrderNo.getText().toString());
        }
    }

    @Override
    public void setRecommend(RecommendRequest request) {
        RecommendDialog recommendDialog=new RecommendDialog(mContext, new RecommendDialog.OnConfrim() {
            @Override
            public void onConfrim() {
                ConfirmEntry confirmEntry = new ConfirmEntry();
                confirmEntry.setConnectionCode(tvConnectionCode.getText().toString());
                confirmEntry.setType("10");
                confirmEntry.setWarehouseId(warehouseBean.getId());
                confirmEntry.setOrderInfos(inStoregeAdapter.getData());
                presenter.confirmEntry(confirmEntry);
            }
        });
        recommendDialog.show(request);
    }

    @Override
    public void setSaveSuccess() {
        if (inStoregeListBean != null){
            inStoregeListBean.setWanNum(etActNum.getText().toString());
            inStoregeListBean.setInNum(etActNum.getText().toString());
        }
        etActNum.setText("");
        etDiskNum.setText("");
        etRemark.setText("");
        tvDate.setText("");
        tvUser.setText("");
        tvProcessName.setText("");
        processBean = null;
        llContent.requestFocus();
    }

    @Override
    public void onSuccess() {
        inStoregeAdapter.setNewInstance(new ArrayList<>());
        tvWarehouseId.setText("");
        tvConnectionCode.setText("");
        tvWarehouseId.setText("");
        tvConnection.setText("");
        warehouseBean = null;
    }


    @OnClick({R.id.iv_close, R.id.tv_back, R.id.tv_work_surface, R.id.tv_warehouseId, R.id.tv_processName, R.id.tv_move_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                finishActivity();
                break;
            case R.id.tv_back:
                finishActivity();
                break;
            case R.id.tv_work_surface:
                presenter.getCenterByUserId();
                break;
            case R.id.tv_warehouseId:
                if (inStoregeAdapter.getData().size() == 0) {
                    showMessage("请先扫订单！");
                    return;
                }
                presenter.getConnectionByCenter(getOrders());
               // presenter.getConnectionByCenter(faceBean.getId());
                break;
            case R.id.tv_processName:
                if (TextUtils.isEmpty(tvOrderNo.getText())) {
                    showMessage("生产订单号不能为空！");
                    return;
                }
                if (TextUtils.isEmpty(tvWorkSurface.getText())) {
                    showMessage("请先选择工作中心！");
                    return;
                }
                presenter.getCenterList(tvOrderNo.getText().toString(), faceBean.getId());
                break;
            case R.id.tv_move_out:
                if (TextUtils.isEmpty(tvWarehouseId.getText().toString())) {
                    showMessage("请先选择线边库");
                    return;
                }
                if (TextUtils.isEmpty(tvConnectionCode.getText().toString())) {
                    showMessage("请先扫接驳工位");
                    return;
                }
                if (inStoregeAdapter.getData().size() == 0) {
                    showMessage("请先选择工单");
                    return;
                }
                if (getInStorege()) {
                    showMessage("请补齐工单信息");
                    return;
                }
                if (getIsNum() && inStoregeAdapter.getData().size() > 1){
                    showMessage("拆托订单，不允许和其他订单合托！");
                    return;
                }
                RecommendRequest recommendRequest=new RecommendRequest();
                recommendRequest.setType("10");
                recommendRequest.setConnectionCode(tvConnectionCode.getText().toString());
                recommendRequest.setWarehouseId(warehouseBean.getId());
                List<RecommendRequest.OrderInfosBean> list=new ArrayList<>();
                for (InStoregeListBean listBean:inStoregeAdapter.getData()){
                    RecommendRequest.OrderInfosBean orderInfosBean=new RecommendRequest.OrderInfosBean();
                    orderInfosBean.setProOrderNo(listBean.getProOrderNo());
                    orderInfosBean.setManzSpecId(listBean.getManzSpecId());
                    orderInfosBean.setFlowId(listBean.getFlowId());
                    orderInfosBean.setInNum(listBean.getInNum());
                    orderInfosBean.setManzSpecName(listBean.getManzSpecName());
                    list.add(orderInfosBean);
                }
                recommendRequest.setOrderInfos(list);
                presenter.recommendBin(recommendRequest);
               /* AffirmDialog affirmDialog = new AffirmDialog(mContext, new AffirmDialog.OnConfrim() {
                    @Override
                    public void onConfrim() {
                        ConfirmEntry confirmEntry = new ConfirmEntry();
                        confirmEntry.setConnectionCode(tvConnectionCode.getText().toString());
                        confirmEntry.setType("10");
                        confirmEntry.setWarehouseId(warehouseBean.getId());
                        confirmEntry.setOrderInfos(inStoregeAdapter.getData());
                        presenter.confirmEntry(confirmEntry);
                    }
                });
                affirmDialog.show("确认入库吗");*/
                break;
        }
    }

    private boolean getInStorege() {
        boolean is = false;
        for (InStoregeListBean listBean : inStoregeAdapter.getData()) {
            if (TextUtils.isEmpty(listBean.getInNum())) {
                is = true;
                break;
            }
        }
        return is;
    }
    private boolean getIsNum(){
        boolean is=false;
        for (InStoregeListBean listBean : inStoregeAdapter.getData()) {
            if (!listBean.getInNum().equals(listBean.getWanNum())) {
                is = true;
                break;
            }
        }
        return is;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.tv_detail)
    public void onViewClicked() {
        if (TextUtils.isEmpty(tvOrderNo.getText().toString())) {
            showMessage("请先扫生产订单码");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("order", tvOrderNo.getText().toString());
        startIntent(AppActivityKey.ORDERDETAILACTIVITY, bundle);
    }

    @OnClick(R.id.tv_user)
    public void onViewClicked1() {
        if (processBean == null) {
            showMessage("请先选择工序！");
            return;
        }
        presenter.getUserByCenterCode(faceBean.getId());
    }

    @OnClick(R.id.tv_date)
    public void onViewClicked2() {
        if (processBean == null) {
            showMessage("请先选择工序！");
            return;
        }
        mDatePicker.show(System.currentTimeMillis(), tvDate);
    }

    private CustomDatePicker mDatePicker;

    private void initDatePicker() {
        long beginTimestamp = DateFormatUtils.str2Long("2000-01-01", false);
        long endTimestamp = DateFormatUtils.str2Long("2500-01-01", false);
        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(mContext, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp, TextView v) {
                v.setText(getYearDateTime(timestamp));
            }
        }, beginTimestamp, endTimestamp);
    }

    /**
     * 将long转换为日期（yyyy-MM-dd HH:mm）
     *
     * @param dateTime
     * @return 到分
     */
    @SuppressLint("SimpleDateFormat")
    public static String getYearDateTime(long dateTime) {
        String time = "";
        try {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            time = sDateFormat.format(new Date(dateTime + 0));
        } catch (Exception e) {

        }
        return time;
    }

    /**
     * 将long转换为日期（yyyy-MM-dd HH:mm）
     *
     * @param dateTime
     * @return 到分
     */
    @SuppressLint("SimpleDateFormat")
    public static String getFormatedDateTime(long dateTime) {
        String time = "";
        try {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("MM");
            time = sDateFormat.format(new Date(dateTime + 0));
        } catch (Exception e) {

        }
        return time;
    }

    @OnClick(R.id.tv_save)
    public void onViewClicked3() {
        if (TextUtils.isEmpty(etActNum.getText().toString())) {
            showMessage("实际产量不能为空！");
            return;
        }
        if (TextUtils.isEmpty(etDiskNum.getText().toString())) {
            showMessage("盘数不能为空！");
            return;
        }
        if (TextUtils.isEmpty(tvUser.getText().toString())) {
            showMessage("工号不能为空！");
            return;
        }
        if (TextUtils.isEmpty(tvDate.getText().toString())) {
            showMessage("日期不能为空！");
            return;
        }
        if (TextUtils.isEmpty(tvProcessName.getText().toString())) {
            showMessage("工序不能为空！");
            return;
        }
        AffirmDialog affirmDialog = new AffirmDialog(mContext, new AffirmDialog.OnConfrim() {
            @Override
            public void onConfrim() {
                CompleteRequest request = new CompleteRequest();
                request.setActNum(Integer.parseInt(etActNum.getText().toString()));
                request.setDiskNum(Integer.parseInt(etDiskNum.getText().toString()));
                request.setUserIds(tvUser.getText().toString());
                request.setProOrderNo(tvOrderNo.getText().toString());
                request.setProcessId(processBean.getId());
                request.setCompleteTime(tvDate.getText().toString());
                request.setRemark(etRemark.getText().toString());
                presenter.confirmComplete(request);
            }
        });
        affirmDialog.show("确认要保存吗？");

    }
}
